{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 事件驱动策略分析\n",
    "\n",
    "本笔记本实现基于事件驱动的量化策略"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import akshare as ak\n",
    "import matplotlib.pyplot as plt\n",
    "from datetime import datetime, timedelta\n",
    "\n",
    "# 设置中文显示\n",
    "plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "plt.rcParams['axes.unicode_minus'] = False"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 财报事件策略"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def earnings_announcement_strategy(stock_code, window=5):\n",
    "    \"\"\"\n",
    "    财报公告事件策略\n",
    "    \n",
    "    Args:\n",
    "        stock_code: 股票代码\n",
    "        window: 事件窗口(天)\n",
    "        \n",
    "    Returns:\n",
    "        pd.DataFrame: 包含事件收益\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 获取财报日期\n",
    "        df = ak.stock_financial_report_sina(stock=stock_code, symbol=\"业绩预告\")\n",
    "        report_dates = pd.to_datetime(df['公告日期']).unique()\n",
    "        \n",
    "        # 获取股价数据\n",
    "        price = ak.stock_zh_a_hist(symbol=stock_code, period=\"daily\", adjust=\"qfq\")\n",
    "        price['日期'] = pd.to_datetime(price['日期'])\n",
    "        price = price.set_index('日期')['收盘']\n",
    "        \n",
    "        # 计算事件收益\n",
    "        results = []\n",
    "        for date in report_dates:\n",
    "            if date in price.index:\n",
    "                idx = price.index.get_loc(date)\n",
    "                start = max(0, idx - window)\n",
    "                end = min(len(price)-1, idx + window)\n",
    "                \n",
    "                window_prices = price.iloc[start:end+1]\n",
    "                returns = window_prices.pct_change().dropna()\n",
    "                \n",
    "                results.append({\n",
    "                    'report_date': date,\n",
    "                    'pre_5d': (window_prices.iloc[-1] / window_prices.iloc[0] - 1) if len(window_prices) > 0 else np.nan,\n",
    "                    'post_5d': (window_prices.iloc[-1] / window_prices.iloc[0] - 1) if len(window_prices) > 0 else np.nan\n",
    "                })\n",
    "        \n",
    "        return pd.DataFrame(results).dropna()\n",
    "    except Exception as e:\n",
    "        print(f\"财报事件策略执行失败: {e}\")\n",
    "        return pd.DataFrame()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 主分析流程"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：分析贵州茅台财报事件\n",
    "result = earnings_announcement_strategy('600519')\n",
    "\n",
    "# 绘制结果\n",
    "if not result.empty:\n",
    "    plt.figure(figsize=(12,6))\n",
    "    result.set_index('report_date')['post_5d'].plot(kind='bar')\n",
    "    plt.title('贵州茅台财报后5日收益率')\n",
    "    plt.axhline(0, color='r', linestyle='--')\n",
    "    plt.ylabel('收益率')\n",
    "    plt.show()\n",
    "else:\n",
    "    print(\"未获取到有效数据\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
   "name": "ipython",
   "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}